﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net;
using System.IO;

using EHTWebsite.Code;
/// <summary>
/// Author: toanvt
/// CreatedDate: 12/12/2011
/// Description: Inser, Update sản phẩm
/// </summary>
public partial class Administrator_AdminProductIU : System.Web.UI.Page
{

    public Int32 SanPhamID = HangSo.DEFAULT_ID;
    private Int32 danhMucSanPhamID = HangSo.DEFAULT_ID;
    private String message = "";
    private DataTable dtProductCategorys = new DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            SanPhamID = Int32.Parse(Request.QueryString["SanPhamID"].ToString());
        }
        catch (Exception)
        {
            SanPhamID = HangSo.DEFAULT_ID;
        }

        try
        {
            danhMucSanPhamID = Int32.Parse(Request.QueryString["danhMucID"].ToString());
        }
        catch (Exception)
        {
            danhMucSanPhamID = HangSo.DEFAULT_ID;
        }

        if (Request.QueryString["Message"] != null)
        {
            try
            {
                message = Request.QueryString["Message"].ToString();
            }
            catch (Exception)
            {
                message = "";
            }
        }

        //hiển thị Message nếu có giá trị Message gửi sang từ màn hình nguồn
        this.lbMessage.Text = message;
        this.lbMessage.CssClass = "BlueCorlor";

        if (!Page.IsPostBack)
        {
            Int32 totalRecord = 0;
           // LoadDataDropDownListNhomSanPham();
            dtProductCategorys = DanhMucSanPhamProvider.GetDanhMucSanPhamsForBackEnd(-1, 1, 100000, out totalRecord).Tables[0];
            // tao danh muc tin tuc trong drop dow list
            CreateDDLCategory(-1, 0);
            this.ddlDanhMuc.Items.Insert(0, new ListItem("----Danh mục sản phẩm----", "-1"));

            if (SanPhamID == -1)
            {
                ViewState["action"] = HangSo.ACTION_ADD;
                ddlDanhMuc.SelectedValue = danhMucSanPhamID.ToString();
                this.btnProductImages.Enabled = false; // ẩn button quản lý danh sách ảnh sản phẩm
                this.lbAdminProductIU.Text = "Thêm mới Sản Phẩm";
            }
            else
            {
                EHTWebsite.Code.SanPham theSanPham = SanPhamProvider.GetSanPhamBySanPhamID(SanPhamID);

                if (theSanPham == null)
                    Response.Redirect("~/Administrator/AdminProducts.aspx");
                else
                {
                    FillDataSanPhamsIntoControls(theSanPham);
                    ViewState["HinhAnhUrl"] = theSanPham.HinhAnhUrl;
                    ViewState["SanPhamID"] = theSanPham.SanPhamID;
                    ViewState["action"] = HangSo.ACTION_UPDATE;
                    this.lbAdminProductIU.Text = "Sửa thông tin Sản Phẩm";
                }
            }

            // Disable Validation cho các Control Other
            if (HangSo.USING_MULTIL_LANGUAGE == false)
            {
                this.rvTenSanPhamOther.Enabled = false;
            }
        }
    }

    /// <summary>
    /// Author: toanvt
    /// CreatedDate: 12/12/2011
    /// Description: Fill dữ liệu sản phẩm vào Control
    /// </summary>
    /// <param name="theSanPham">Đối tượng sản phẩm chứa dữ liệu chỉ định</param>
    private void FillDataSanPhamsIntoControls(EHTWebsite.Code.SanPham theSanPham)
    {
        this.txtTenSanPhamVN.Text = theSanPham.TenSanPhamVN;
        this.txtTenSanPhamOther.Text = theSanPham.TenSanPhamOther;
        this.fckMoTaVN.Value = theSanPham.MoTaVN;
        this.fckMoTaOther.Value = theSanPham.MoTaOther;
        this.txtDonGia.Text = theSanPham.DonGia.ToString();
        this.txtSoLuong.Text = theSanPham.SoLuong.ToString();
        this.txtGiamGia.Text = theSanPham.GiamGia.ToString();
        this.fckNoiDungVN.Value = theSanPham.NoiDungVN.Trim();
        this.fckNoiDungOther.Value = theSanPham.NoiDungOther.Trim();
        this.ddlDanhMuc.SelectedValue = theSanPham.DanhMucID.ToString();
        this.chkNoiBat.Checked = theSanPham.NoiBat;
        this.txtLuotXem.Text = theSanPham.LuotXem.ToString();
        this.txtSapXep.Text = theSanPham.SapXep.ToString();
        this.picHinhAnh.ImageUrl = @"~\ImageDatas\Products\noImage.gif";
        this.ckPublish.Checked = theSanPham.Publish;
        this.ddlDanhMuc.SelectedValue = theSanPham.DanhMucID.ToString();
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Administrator/AdminProducts.aspx?DanhMucID=" + ddlDanhMuc.SelectedValue.ToString());
    }


    /// <summary>
    /// Author: toanvt
    /// CreatedDate: 12/12/2011
    /// Description: Validate dữ liệu nhập
    /// </summary>
    /// <returns>Trạng thái đúng hay không đúng</returns>
    private Boolean ValidateData()
    {
        this.lbMessage.Text = "";
        this.lbMessage.CssClass = "";

        String message = "";
        Boolean isSuccess = true;
        string extendsion = HangSo.IMAGE_VALIDATION;

        if (this.funHinhAnh.HasFile && extendsion.IndexOf(Path.GetExtension(this.funHinhAnh.PostedFile.FileName)) < 0)
        {
            message += "Ảnh đại sản phẩm không đúng <br />";
            isSuccess = false;
        }

        try
        {
            Decimal.Parse(this.txtDonGia.Text.ToString());
        }
        catch (Exception)
        {
            message += "Đơn giá không đúng <br />";
            isSuccess = false;
        }

        try
        {
            Int32.Parse(this.txtSoLuong.Text.ToString());
        }
        catch (Exception)
        {

            message += "Số lượng không đúng <br />";
            isSuccess = false;
        }

        try
        {
            float.Parse(this.txtGiamGia.Text.ToString());
        }
        catch (Exception)
        {
            message += "Giảm giá không đúng <br />";
            isSuccess = false;
        }

        if (!isSuccess)
        {
            ltrMessage.Text = message;
        }

        return isSuccess;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        String action = ViewState["action"].ToString();

        if (!ValidateData())
            return;

        Page.Validate();

        if (Page.IsValid)
        {
            EHTWebsite.Code.SanPham theSanPham = new EHTWebsite.Code.SanPham();
            theSanPham.TenSanPhamVN = this.txtTenSanPhamVN.Text.Trim();
            theSanPham.TenSanPhamOther = this.txtTenSanPhamOther.Text.Trim();
            theSanPham.MoTaVN = this.fckMoTaVN.Value.Trim();
            theSanPham.MoTaOther = this.fckMoTaOther.Value.Trim();
            theSanPham.DonGia = Decimal.Parse(this.txtDonGia.Text.Trim());
            theSanPham.SoLuong = Int32.Parse(this.txtSoLuong.Text.Trim());
            theSanPham.GiamGia = float.Parse(this.txtGiamGia.Text.Trim());
            theSanPham.NoiDungVN = this.fckNoiDungVN.Value;
            theSanPham.NoiDungOther = this.fckNoiDungOther.Value;
            theSanPham.Publish = this.ckPublish.Checked;
            try
            {
                theSanPham.DanhMucID = Int32.Parse(ddlDanhMuc.SelectedValue.ToString());
            }
            catch (Exception)
            {
                theSanPham.DanhMucID = (-1);
            }

            theSanPham.NoiBat = chkNoiBat.Checked;
            theSanPham.SapXep = Int32.Parse(txtSapXep.Text.Trim());
            Boolean isHot = this.ckIsHot.Checked;
            DataSet theDanhMucSanPham = DanhMucSanPhamProvider.GetDanhMucDanhMucSanPhamsByNhomDanhMucID(theSanPham.DanhMucID);
            
            if(theDanhMucSanPham.Tables[0].Rows.Count >1 )
            {
                ltrMessage.Text="Không thể thêm sản phẩm vào chuyên mục cha";
                return;
            }
            
            if (this.funHinhAnh.HasFile)
            {
                String fileName = funHinhAnh.PostedFile.FileName;
                String fileType = Path.GetExtension(fileName);
                String newFileName = DateTime.Now.Ticks.ToString() + fileType;
                this.funHinhAnh.PostedFile.SaveAs(Server.MapPath("~/") + "ImageDatas//Products//" + newFileName);
                theSanPham.HinhAnhUrl = newFileName;
            }
            else
            {
                if (action == HangSo.ACTION_UPDATE)
                {
                    theSanPham.HinhAnhUrl = ViewState["HinhAnhUrl"].ToString();
                }
                else
                {
                    theSanPham.HinhAnhUrl = "noImage.gif";
                }
            }

            if (action == HangSo.ACTION_ADD)
            {
                theSanPham.SanPhamID = -1;
                SanPhamProvider.IUSanPham(theSanPham, isHot, true);
            }
            else
            {
                theSanPham.SanPhamID = Int32.Parse(ViewState["SanPhamID"].ToString());
                SanPhamProvider.IUSanPham(theSanPham, isHot, false);
            }

            Response.Redirect("~/Administrator/AdminProducts.aspx?DanhMucID=" + ddlDanhMuc.SelectedValue.ToString());
        }
    }

    protected void btnProductImages_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Administrator/AdminProductImages.aspx?SanPhamID=" + ViewState["SanPhamID"].ToString());
    }
    /// <summary>
    /// Author:tungvu90
    /// Create Date:08/02/2012
    /// Description:Hiện thị dropbox bằng đệ quy
    /// </summary>
    /// <param name="ChuyenMucChaID"></param>
    /// <param name="level"></param>
    private void CreateDDLCategory(Int32 ChuyenMucChaID, Int32 level)
    {
        String preString = "";

        for (Int32 i = 0; i < level; ++i)
        {
            preString += "--";
        }

        DataRow[] drCategorysSub = dtProductCategorys.Select("ChuyenMucChaID = " + ChuyenMucChaID.ToString());
        Int32 amountOfCategorySub = drCategorysSub.Count();

        //Điểm dừng đệ quy
        if (amountOfCategorySub == 0)
            return;

        for (Int32 i = 0; i < amountOfCategorySub; ++i)
        {
            Int32 subCategoryID = Int32.Parse(drCategorysSub[i]["DanhMucID"].ToString());

            ListItem li = new ListItem(preString + drCategorysSub[i]["TenDanhMucVN"].ToString(), drCategorysSub[i]["DanhMucID"].ToString());
            this.ddlDanhMuc.Items.Add(li);
            CreateDDLCategory(subCategoryID, level + 1);
        }
    }
    /// <summary>
    /// Author:tungvu90
    /// Create Date:08/02/2012
    /// Descript:nút áp dụng cho Danh mục sản phẩm
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        Int32 sanPhamIDOut = -1;
        String action = ViewState["action"].ToString();

        if (!ValidateData())
            return;

        Page.Validate();

        if (Page.IsValid)
        {
            EHTWebsite.Code.SanPham theSanPham = new EHTWebsite.Code.SanPham();
            theSanPham.TenSanPhamVN = this.txtTenSanPhamVN.Text.Trim();
            theSanPham.TenSanPhamOther = this.txtTenSanPhamOther.Text.Trim();
            theSanPham.MoTaVN = this.fckMoTaVN.Value.Trim();
            theSanPham.MoTaOther = this.fckMoTaOther.Value.Trim();
            theSanPham.DonGia = Decimal.Parse(this.txtDonGia.Text.Trim());
            theSanPham.SoLuong = Int32.Parse(this.txtSoLuong.Text.Trim());
            theSanPham.GiamGia = float.Parse(this.txtGiamGia.Text.Trim());
            theSanPham.NoiDungVN = this.fckNoiDungVN.Value;
            theSanPham.NoiDungOther = this.fckNoiDungOther.Value;
            theSanPham.Publish = this.ckPublish.Checked;

            try
            {
                theSanPham.DanhMucID = Int32.Parse(ddlDanhMuc.SelectedValue.ToString());
            }
            catch (Exception)
            {
                theSanPham.DanhMucID = (-1);
            }

            theSanPham.NoiBat = chkNoiBat.Checked;
            theSanPham.SapXep = Int32.Parse(txtSapXep.Text.Trim());
            Boolean isHot = this.ckIsHot.Checked;

            if (this.funHinhAnh.HasFile)
            {
                String fileName = funHinhAnh.PostedFile.FileName;
                String fileType = Path.GetExtension(fileName);
                String newFileName = DateTime.Now.Ticks.ToString() + fileType;
                this.funHinhAnh.PostedFile.SaveAs(Server.MapPath("~/") + "ImageDatas//Products//" + newFileName);
                theSanPham.HinhAnhUrl = newFileName;
            }
            else
            {
                if (action == HangSo.ACTION_UPDATE)
                {
                    theSanPham.HinhAnhUrl = ViewState["HinhAnhUrl"].ToString();
                }
                else
                {
                    theSanPham.HinhAnhUrl = "noImage.gif";
                }
            }

            if (action == HangSo.ACTION_ADD)
            {
                theSanPham.SanPhamID = -1;
                sanPhamIDOut = SanPhamProvider.IUSanPham(theSanPham, isHot, true);
            }
            else
            {
                theSanPham.SanPhamID = Int32.Parse(ViewState["SanPhamID"].ToString());
                sanPhamIDOut = SanPhamProvider.IUSanPham(theSanPham, isHot, false);
            }

            Response.Redirect("AdminProductIU.aspx?SanPhamID=" + sanPhamIDOut.ToString() + "&Message=Lưu thành công");
        }
    }
}
